﻿using System;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.ServiceLocation;

namespace UltimateNavigationFramework.UriNavigation
{
    public class UltimateNavigationFrameRegionAdapter : RegionAdapterBase<UltimateNavigationFrame>
    {
        public UltimateNavigationFrameRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
            : base(regionBehaviorFactory)
        {

        }

        protected override void Adapt(IRegion region, UltimateNavigationFrame regionTarget)
        {
            if (regionTarget == null)
            {
                throw new ArgumentNullException("regionTarget");
            }

            region.NavigationService = new UltimateRegionNavigationService(
                            ServiceLocator.Current.GetInstance<IUltimateRegionNavigationJournal>()) { Frame = regionTarget, Region = region };
        }

        /// <summary>
        /// Attaches the Behavior
        /// </summary>
        /// <param name="region">The region.</param>
        /// <param name="regionTarget">The region target.</param>
        protected override void AttachBehaviors(IRegion region, UltimateNavigationFrame regionTarget)
        {
            if (region == null)
                throw new ArgumentNullException("region"); 

            base.AttachBehaviors(region, regionTarget);

            if (!region.Behaviors.ContainsKey(UltimateNavigationFrameRegionBehavior.BehaviorKey))
            {
                if (!region.Behaviors.ContainsKey(UltimateNavigationFrameRegionBehavior.BehaviorKey))
                    region.Behaviors.Add(UltimateNavigationFrameRegionBehavior.BehaviorKey, new UltimateNavigationFrameRegionBehavior { HostControl = regionTarget });     
            }
        }

        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }
    }
}
